package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@ResponseBody
@Slf4j
//默认拦截所有Controller发出的异常
@ControllerAdvice(annotations = {RestController.class, Controller.class})

//默认拦截所有RestController发出的异常,并且有具有@ResponseBody
//@ResponseBody将相应的数据转成JSON格式返回到响应体数据中
//@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        String[] split = message.split(" ");
        if (message.contains("Duplicate entry")){

            String msg = split[2]+ "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");



     /*log.error(ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String msg = split[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");*/
    }
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
